import { useState } from 'react';
import { useFlowStore } from '../../stores/flowStore';

interface ConnectionPoints {
  start: { x: number; y: number };
  end: { x: number; y: number };
}

const NODE_WIDTH = 120;
const NODE_HEIGHT = 80;

// 计算两个节点之间最优的连接点位置
const getAdaptiveConnectionPoints = (
  sourcePos: { x: number; y: number },
  targetPos: { x: number; y: number }
): ConnectionPoints => {
  const dx = targetPos.x - sourcePos.x;
  const dy = targetPos.y - sourcePos.y;
  
  const horizontalDirection = dx >= 0 ? 'right' : 'left';
  const verticalDirection = dy >= 0 ? 'down' : 'up';

  // 确定连接点出口方向
  if (Math.abs(dx) > Math.abs(dy) * 2) { // 主要水平方向
    return {
      start: { 
        x: sourcePos.x + (horizontalDirection === 'right' ? NODE_WIDTH : 0),
        y: sourcePos.y + NODE_HEIGHT / 2 
      },
      end: { 
        x: targetPos.x + (horizontalDirection === 'right' ? 0 : NODE_WIDTH),
        y: targetPos.y + NODE_HEIGHT / 2 
      }
    };
  } else { // 主要垂直方向或对角线
    return {
      start: { 
        x: sourcePos.x + NODE_WIDTH / 2,
        y: sourcePos.y + (verticalDirection === 'down' ? NODE_HEIGHT : 0)
      },
      end: {
        x: targetPos.x + NODE_WIDTH / 2,
        y: targetPos.y + (verticalDirection === 'down' ? 0 : NODE_HEIGHT)
      }
    };
  }
};

// 贝塞尔路径计算函数，用于平滑连接
const calculateBezierPath = (start: { x: number; y: number }, end: { x: number; y: number }): string => {
  const dx = end.x - start.x;
  const dy = end.y - start.y;
  
  // 动态计算控制点
  const cx1 = start.x + dx * 0.4;
  const cy1 = start.y + dy * 0.1;
  const cx2 = start.x + dx * 0.6;
  const cy2 = start.y + dy * 0.9;

  return `M ${start.x} ${start.y} C ${cx1} ${cy1}, ${cx2} ${cy2}, ${end.x} ${end.y}`;
};

export const ConnectionRenderer = () => {
  const connections = useFlowStore((state) => state.connections);
  const nodes = useFlowStore((state) => state.nodes);
  const [hoveredEdge, setHoveredEdge] = useState<string | null>(null);

  const getConnectionPath = (conn: FlowConnection) => {
    const sourceNode = nodes.find(n => n.id === conn.sourceId);
    const targetNode = nodes.find(n => n.id === conn.targetId);
    if (!sourceNode || !targetNode) return null;

    const { start, end } = getAdaptiveConnectionPoints(
      sourceNode.position,
      targetNode.position
    );

    return {
      path: calculateBezierPath(start, end),
      sourceDir: start.x > sourceNode.position.x + NODE_WIDTH / 2 ? 'right' : 'left',
      targetDir: end.x > targetNode.position.x + NODE_WIDTH / 2 ? 'right' : 'left'
    };
  };

  return (
    <svg className="connections-layer">
      <defs>
        <marker id="arrowhead-right" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
          <polygon points="0 0, 10 3.5, 0 7" fill="#409EFF" />
        </marker>
        <marker id="arrowhead-left" markerWidth="10" markerHeight="7" refX="1" refY="3.5" orient="auto">
          <polygon points="10 0, 0 3.5, 10 7" fill="#409EFF" />
        </marker>
      </defs>
      
      {connections.map((conn) => {
        const pathInfo = getConnectionPath(conn);
        if (!pathInfo) return null;
        
        return (
          <path
            key={conn.id}
            d={pathInfo.path}
            className={`connection ${hoveredEdge === conn.id ? 'highlight' : ''}`}
            stroke="#409EFF"
            fill="none"
            strokeWidth={hoveredEdge === conn.id ? 3 : 2}
            markerEnd={`url(#arrowhead-${pathInfo.targetDir})`}
            onMouseEnter={() => setHoveredEdge(conn.id)}
            onMouseLeave={() => setHoveredEdge(null)}
            onClick={(e) => {
              e.stopPropagation();
              // 可以添加连接线点击逻辑
            }}
          />
        );
      })}
    </svg>
  );
};